<script setup>
import { ref, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { findAllDepartments, addDepartment, updateDepartment, deleteDepartment } from '../api/departmentApi.js';

// 表格数据
const departmentList = ref([]);
// 控制对话框显示
const dialogVisible = ref(false);
// 对话框表单数据
const form = ref({
  deptId: null,
  name: '',
  status: 1
});
// 判断是新增还是编辑
const isEdit = ref(false);

// 加载表格数据
const loadData = async () => {
  let response = await findAllDepartments();
  departmentList.value = response.data.data;
};

// 在组件挂载后加载数据
onMounted(() => {
  loadData();
});

// 处理新增按钮点击
const handleAdd = () => {
  isEdit.value = false;
  form.value = { deptId: null, name: '', status: 1 };
  dialogVisible.value = true;
};

// 处理编辑按钮点击
const handleEdit = (row) => {
  isEdit.value = true;
  form.value = { ...row }; // 复制行数据到表单
  dialogVisible.value = true;
};

// 处理状态变更（启用/禁用）
const handleStatusChange = async (row) => {
  const newStatus = row.status === 1 ? 0 : 1;
  const text = newStatus === 1 ? '启用' : '禁用';
  try {
    await ElMessageBox.confirm(`你确定要${text} [${row.name}] 吗?`, '温馨提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    });
    // 调用更新接口
    await updateDepartment({ ...row, status: newStatus });
    ElMessage.success(`${text}成功!`);
    loadData(); // 重新加载数据
  } catch (error) {
    ElMessage.info(`已取消${text}操作`);
  }
};

// 处理删除按钮点击
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm(`你确定要删除 [${row.name}] 吗?`, '危险操作', {
      confirmButtonText: '确认删除',
      cancelButtonText: '取消',
      type: 'error',
    });
    const res = await deleteDepartment(row.deptId);
    if (res.data.code === 200) {
      ElMessage.success('删除成功!');
      loadData(); // 重新加载数据
    } else {
      ElMessage.error(res.data.msg); // 显示后端返回的错误信息
    }
  } catch (error) {
    ElMessage.info('已取消删除');
  }
};

// 提交表单（新增或编辑）
const submitForm = async () => {
  if (!form.value.name) {
    ElMessage.error('部门名称不能为空');
    return;
  }

  if (isEdit.value) {
    // 编辑
    const res = await updateDepartment(form.value);
    if (res.data.code === 200) {
      ElMessage.success('更新成功!');
    } else {
      ElMessage.error(res.data.msg);
    }
  } else {
    // 新增
    const res = await addDepartment(form.value);
    if (res.data.code === 200) {
      ElMessage.success('添加成功!');
    } else {
      ElMessage.error(res.data.msg);
    }
  }
  dialogVisible.value = false;
  loadData(); // 刷新表格
};

</script>

<template>
  <div>
    <div style="margin-bottom: 15px;">
      <el-button type="primary" @click="handleAdd">新增部门</el-button>
    </div>

    <el-table :data="departmentList" border stripe style="width: 100%">
      <el-table-column prop="deptId" label="部门ID" width="100" />
      <el-table-column prop="name" label="部门名称" />
      <el-table-column label="状态" width="120">
        <template #default="{ row }">
          <el-tag :type="row.status === 1 ? 'success' : 'danger'">
            {{ row.status === 1 ? '启用' : '禁用' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="280">
        <template #default="{ row }">
          <el-button size="small" type="primary" @click="handleEdit(row)">编辑</el-button>
          <el-button size="small" :type="row.status === 1 ? 'warning' : 'success'" @click="handleStatusChange(row)">
            {{ row.status === 1 ? '禁用' : '启用' }}
          </el-button>
          <el-button size="small" type="danger" @click="handleDelete(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog v-model="dialogVisible" :title="isEdit ? '编辑部门' : '新增部门'" width="30%">
      <el-form :model="form" label-width="80px">
        <el-form-item label="部门名称">
          <el-input v-model="form.name" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>